﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using TyNetCoreBlog.Helpers;
using TyNetCoreBlog.Models.Dto.FriendlyLink;
using TyNetCoreBlog.Repository.RepositoryWrapper;
using static TyNetCoreBlog.Helpers.ResponseMsg;

namespace TyNetCoreBlog.Controllers
{
    [Route("api/friendlylinks")]
    [EnableCors("any")]
    [ApiController]
    public class FriendlylinkController : Controller
    {
        private readonly IRepositoryWrapper _repositoryWrapper;
        private readonly IMapper _mapper;

        public FriendlylinkController(IRepositoryWrapper repositoryWrapper, IMapper mapper)
        {
            this._repositoryWrapper = repositoryWrapper ?? throw new ArgumentNullException(nameof(repositoryWrapper));
            this._mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }

        
        /// <summary>
        /// 获取所有友链
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ResponseCache(Duration = 3)]
        public async Task<ActionResult<IEnumerable<FriendlyLinkDto>>> GetFriendlylinks()
        {
            var flinks = await _repositoryWrapper.Friendlylink.GetAllAsync();
            var flinkDtoList = _mapper.Map<IEnumerable<FriendlyLinkDto>>(flinks).ToList();
            return Ok(new ResponseMsg(ApiStatus.OK, flinkDtoList));
        }
        
        
        /// <summary>
        /// 通过id获取一个友链
        /// </summary>
        /// <param name="flinkId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{flinkId}", Name = nameof(GetOneFriendlylink))]
        [ResponseCache(Duration = 3)]
        public async Task<ActionResult<FriendlyLinkDto>> GetOneFriendlylink(int flinkId)
        {
            var flink = await _repositoryWrapper.Friendlylink.GetByIdAsync(flinkId);
            if (flink == null)
            {
                return NotFound(new ResponseMsg(ApiStatus.NotFound));
            }
            var flDto = _mapper.Map<FriendlyLinkDto>(flink);
            return Ok(new ResponseMsg(ApiStatus.OK, flDto));
        }
        
    }
}